
package com.kanjian.music.fragment;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.kanjian.music.R;
import com.kanjian.music.activity.BaseActivity;
import com.kanjian.music.adapter.LiveListAdapter;
import com.kanjian.music.api.ApiRequestManager;
import com.kanjian.music.constants.IntentConstants;
import com.kanjian.music.entity.Live;
import com.kanjian.music.network.HttpLoader;

/**
 * 直播
 * 
 * @author xuyanjun@kanjian.com
 */
public class LiveListFragment extends BaseFragment implements LoaderCallbacks<String> {

    private View mRootView;

    private ListView mListView;

    private LiveListAdapter mListAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initView(inflater, container);
        return mRootView;
    }

    private void initView(LayoutInflater inflater, ViewGroup container) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.fragment_live, container, false);
            mListView = (ListView) mRootView.findViewById(R.id.live_listview);
            mListAdapter = new LiveListAdapter((BaseActivity) getActivity(), mListView);
            mListView.setAdapter(mListAdapter);
            Bundle args = new Bundle();
            args.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM,
                    ApiRequestManager.getActivityRequest());
            getLoaderManager().restartLoader(0, args, this);
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mRootView != null) {
            ViewGroup parentViewGroup = (ViewGroup) mRootView.getParent();
            if (parentViewGroup != null) {
                parentViewGroup.removeAllViews();
            }
        }
    }

    @Override
    public Loader<String> onCreateLoader(int id, Bundle args) {
        return new HttpLoader(getActivity(), args);
    }

    @Override
    public void onLoadFinished(Loader<String> loader, String data) {
        if (data != null) {
            ArrayList<Live> mLiveList = Live.getLiveListFromJson(data);
            if (mLiveList != null) {
                mListAdapter.setLiveList(mLiveList);
                mListAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<String> loader) {
    }

}
